#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;

const int kInf = 1e9;

vector<vector<int>> g;
vector<int> dist;

int BFS(int b, int e, int n) {
  queue<int> que;

  dist.clear();
  dist.resize(n + 1, kInf);
  dist[b] = 0;
  que.emplace(b);
  for (; dist[e] == kInf && !que.empty(); que.pop()) {
    int now = que.front();

    for (int next : g[now]) {
      if (dist[next] == kInf) {
        dist[next] = dist[now] + 1;
        que.emplace(next);
      }
    }
  }
  return dist[e] / 2;
}

int BuildNewGraph() {
  unordered_map<int, int> colors_id;
  vector<vector<pair<int, int>>> old_graph;
  int n, m;
  int ret;

  cin >> n >> m;

  ret = n;
  old_graph.resize(n + 1, vector<pair<int, int>>());

  for (int i = 0; i < m; i++) {
    int u, v, c;

    cin >> u >> v >> c;
    old_graph[u].emplace_back(v, c);
    old_graph[v].emplace_back(u, c);
    if (colors_id.count(c) == 0) {
      colors_id[c] = ++ret;
    }
  }

  g.clear();
  g.resize(ret + 1);
  for (int i = 1; i <= n; i++) {
    for (const pair<int, int> &edge : old_graph[i]) {
      g[edge.first].emplace_back(colors_id[edge.second]);
      g[colors_id[edge.second]].emplace_back(edge.first);
    }
  }
  return ret;
}

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int T;

  for (cin >> T; T; T--) {
    int n = BuildNewGraph();
    int b, e;

    cin >> b >> e;
    cout << BFS(b, e, n) << "\n";
  }
  return 0;
}